package socket;
/*
服务端
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//它运行在服务端，如果我们将socket比喻为查电话的插座，那么这个就相当于  “总机”


public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    public Server(){
        try{
            System.out.println("启动服务器");
            serverSocket = new ServerSocket(8088);
            threadPool = Executors.newFixedThreadPool(40);
            System.out.println("服务器启动成功");
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void start() {
        try{
            while (true){
                System.out.println("等待客户连接");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户已接入");
                ClientHandler clientHandler = new ClientHandler(socket);
//                Thread t1 = new Thread(clientHandler);

//                t1.start();

                threadPool.execute(clientHandler);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    class ClientHandler implements Runnable{
        private Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            try{
                InputStream in = socket.getInputStream();
                int a;
                while ((a=in.read()) != -1){
                    byte[] data = new byte[a];
                    in.read(data);
                    String s = new String(data,StandardCharsets.UTF_8);
                    System.out.println(s);
                }
            }catch (Exception e){
                //e.printStackTrace();
            }finally {
                System.out.println("客户端下线了");
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}
